'use client'

import React, { useState, useEffect, useCallback } from 'react'
import { useParams } from 'next/navigation'
import { useSession } from 'next-auth/react'
import { formatDate } from '@/lib/utils'
import ResourceUploader from '@/components/experiments/ResourceUploader'
import AnnouncementList from '@/components/experiments/AnnouncementList'
import Button from '@/components/ui/Button'
import ButtonLink from '@/components/ui/ButtonLink'
import { toast } from 'react-hot-toast'
import debounce from 'lodash/debounce'
import GradeInput from '@/components/experiments/GradeInput'
import GroupGradeInput from '@/components/experiments/GroupGradeInput'
import HistoryView from '@/components/experiments/HistoryView'

interface Experiment {
  id: string
  title: string
  description: string
  startTime: string
  endTime: string
  allowLateSubmission: boolean
  stages: Array<Omit<Stage, 'content'> & { content: string | object }>
  authorizedExperiments: {
    student: {
      id: string
      name: string | null
      email: string
    }
  }[]
  resources: Resource[]
  createdBy: {
    id: string
    name: string
    email: string
  }
}

interface Stage {
  id: string
  title: string
  description: string
  type: string
  order: number
  content: any
}

interface Resource {
  id: string
  title: string
  type: string
  url: string
  createdAt: string
}

interface Submission {
  id: string
  status: string
  score: number | null
  stageSubmissions: StageSubmission[]
}

interface StageSubmission {
  id: string
  stageId: string
  answer: any
  score: number | null
  feedback: string | null
  submittedAt: string | null
  stage: Stage
}

interface ResourceUploaderProps {
  experimentId: string;
  resources: Resource[];
  onResourceAdded?: (resource: Resource) => void;
  onResourceDeleted?: (resourceId: string) => void;
  canManage?: boolean;
}

export default function ExperimentDetailPage() {
  const params = useParams()
  const { data: session, status } = useSession()
  const [experiment, setExperiment] = useState<Experiment | null>(null)
  const [submission, setSubmission] = useState<Submission | null>(null)
  const [activeTab, setActiveTab] = useState('overview')
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState('')
  const [loadAttempts, setLoadAttempts] = useState(0)
  const [studentSubmissions, setStudentSubmissions] = useState<any[]>([])
  const [submissionStats, setSubmissionStats] = useState<{
    totalSubmissions: number;
    totalStudents: number;
    submissionRate: number;
    statusCounts: {
      IN_PROGRESS: number;
      SUBMITTED: number;
      GRADED: number;
    };
    avgScoreOfHighestSubmissions: number | null;
    studentsWhoSubmittedAtLeastOnce: number;
    totalAuthorizedStudents: number;
    totalFormalSubmissions: number;
  } | null>(null)
  const [loadingSubmissions, setLoadingSubmissions] = useState(false)
  const [submissionError, setSubmissionError] = useState('')
  const [scrollTimeout, setScrollTimeout] = useState(null)
  const [viewMode, setViewMode] = useState<'individual' | 'group'>('individual')
  const [groupSubmissions, setGroupSubmissions] = useState<any[]>([])
  const [loadingGroups, setLoadingGroups] = useState(false)

  const experimentId = params.id as string

  useEffect(() => {
    if (status === 'loading') return

    const fetchExperiment = async () => {
      try {
        setLoading(true)
        console.log(`尝试获取实验详情，实验ID: ${experimentId}，尝试次数: ${loadAttempts + 1}`)
        
        const response = await fetch(`/api/experiments/${experimentId}`)
        
        console.log(`API 响应状态: ${response.status}`)
        
        if (!response.ok) {
          const errorData = await response.json().catch(() => ({}))
          const errorMessage = errorData.message || `获取实验详情失败 (${response.status})`
          console.error(`获取实验详情失败:`, errorMessage)
          throw new Error(errorMessage)
        }
        
        const data = await response.json()
        console.log('获取到实验数据:', data)
        
        setExperiment(data.experiment)
        
        if (data.submission) {
          setSubmission(data.submission)
        }
      } catch (err: any) {
        console.error('获取实验详情错误:', err)
        setError(err.message || '获取实验详情失败，请稍后重试')
        
        // 如果是未授权错误，不再重试
        if (err.message?.includes('未授权') || err.message?.includes('无权访问')) {
          toast.error('您没有权限查看此实验')
        } else if (loadAttempts < 2) {
          // 最多重试两次
          setTimeout(() => {
            setLoadAttempts(prev => prev + 1)
          }, 1000)
        }
      } finally {
        setLoading(false)
      }
    }

    fetchExperiment()
  }, [experimentId, status, loadAttempts])

  const handleResourceAdded = useCallback((newResource: Resource) => {
    setExperiment(prevExperiment => {
      if (!prevExperiment) return null;
      // 按创建时间降序（新的在前面）或按标题排序等
      const updatedResources = [...(prevExperiment.resources || []), newResource].sort((a, b) => new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime());
      return {
        ...prevExperiment,
        resources: updatedResources,
      };
    });
    toast.success('资源已成功添加！');
  }, []);

  const handleResourceDeleted = useCallback((deletedResourceId: string) => {
    setExperiment(prevExperiment => {
      if (!prevExperiment) return null;
      return {
        ...prevExperiment,
        resources: (prevExperiment.resources || []).filter(res => res.id !== deletedResourceId),
      };
    });
    toast.success('资源已成功删除！');
  }, []);

  const isTeacherOrAdmin = session?.user?.role === 'TEACHER' || session?.user?.role === 'ADMIN'
  const isExperimentOwner = experiment?.createdBy.id === session?.user?.id
  const canManageExperimentResources = isTeacherOrAdmin && (isExperimentOwner || session?.user?.role === 'ADMIN')

  const fetchStudentSubmissions = useCallback(
    debounce(async () => {
      if (activeTab !== 'students') return;
      
      try {
        setLoadingSubmissions(true);
        setSubmissionError('');
        
        const response = await fetch(`/api/experiments/${experimentId}/submit`);
        
        if (!response.ok) {
          const errorData = await response.json().catch(() => ({}));
          throw new Error(errorData.message || `获取学生提交情况失败 (${response.status})`);
        }
        
        const data = await response.json();
        setStudentSubmissions(data.submissions || []);
        setSubmissionStats(data.stats);
      } catch (err: any) {
        console.error('获取学生提交情况错误:', err);
        setSubmissionError(err.message || '获取学生提交情况失败，请稍后重试');
      } finally {
        setLoadingSubmissions(false);
      }
    }, 300),
    [experimentId, activeTab]
  );

  const fetchGroupSubmissions = useCallback(
    debounce(async () => {
      if (activeTab !== 'students' || viewMode !== 'group') return;
      
      try {
        setLoadingGroups(true);
        setSubmissionError('');
        
        const response = await fetch(`/api/experiments/${experimentId}/groups`);
        
        if (!response.ok) {
          const errorData = await response.json().catch(() => ({}));
          throw new Error(errorData.message || `获取小组信息失败 (${response.status})`);
        }
        
        const data = await response.json();
        setGroupSubmissions(data.groups);
      } catch (err: any) {
        console.error('获取小组信息错误:', err);
        setSubmissionError(err.message || '获取小组信息失败，请稍后重试');
      } finally {
        setLoadingGroups(false);
      }
    }, 300),
    [experimentId, activeTab, viewMode]
  );

  // 获取状态文本
  const getStatusText = (status: string) => {
    switch (status) {
      case 'IN_PROGRESS': return '进行中'
      case 'SUBMITTED': return '已提交'
      case 'GRADED': return '已评分'
      default: return status
    }
  }

  // 处理单个学生成绩更新
  const handleScoreUpdate = (submissionId: string, newScore: number | null) => {
    setStudentSubmissions(prev => 
      prev.map(submission => 
        submission.id === submissionId 
          ? { ...submission, score: newScore, status: 'GRADED' }
          : submission
      )
    )
    
    // 更新统计信息
    if (submissionStats) {
      const updatedSubmissions = studentSubmissions.map(submission => 
        submission.id === submissionId 
          ? { ...submission, score: newScore, status: 'GRADED' }
          : submission
      )
      
      const gradedSubmissions = updatedSubmissions.filter(s => s.score !== null)
      const avgScore = gradedSubmissions.length > 0 
        ? gradedSubmissions.reduce((sum, s) => sum + (s.score || 0), 0) / gradedSubmissions.length
        : null
      
      setSubmissionStats(prev => prev ? {
        ...prev,
        statusCounts: {
          ...prev.statusCounts,
          GRADED: gradedSubmissions.length,
          SUBMITTED: Math.max(0, prev.statusCounts.SUBMITTED - (newScore !== null ? 1 : 0))
        },
        avgScoreOfHighestSubmissions: avgScore
      } : null)
    }
  }

  // 处理小组成绩批量更新
  const handleGroupScoresUpdate = (updates: { submissionId: string; score: number }[]) => {
    setStudentSubmissions(prev => 
      prev.map(submission => {
        const update = updates.find(u => u.submissionId === submission.id)
        return update 
          ? { ...submission, score: update.score, status: 'GRADED' }
          : submission
      })
    )
    
    // 刷新统计信息
    fetchStudentSubmissions()
  }

  // 当切换到学生选项卡时加载数据
  useEffect(() => {
    if (activeTab === 'students' && isTeacherOrAdmin && experimentId) {
      if (viewMode === 'individual') {
        fetchStudentSubmissions();
      } else {
        fetchGroupSubmissions();
      }
    }
  }, [activeTab, isTeacherOrAdmin, experimentId, viewMode, fetchStudentSubmissions, fetchGroupSubmissions]);

  useEffect(() => {
    return () => {
      setStudentSubmissions([]);
      setSubmissionStats(null);
    };
  }, []);

  if (loading) {
    return (
      <div className="py-8">
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
          <div className="text-center py-16">
            <div className="flex justify-center">
              <div className="animate-spin rounded-full h-12 w-12 border-t-2 border-b-2 border-primary-600"></div>
            </div>
            <p className="mt-4 text-gray-600">加载实验详情中...</p>
          </div>
        </div>
      </div>
    )
  }

  if (error) {
    return (
      <div className="py-8">
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
          <div className="bg-red-50 border border-red-200 rounded-md p-4">
            <div className="flex">
              <div className="flex-shrink-0">
                <svg className="h-5 w-5 text-red-400" viewBox="0 0 20 20" fill="currentColor">
                  <path fillRule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zM8.707 7.293a1 1 0 00-1.414 1.414L8.586 10l-1.293 1.293a1 1 0 101.414 1.414L10 11.414l1.293 1.293a1 1 0 001.414-1.414L11.414 10l1.293-1.293a1 1 0 00-1.414-1.414L10 8.586 8.707 7.293z" clipRule="evenodd" />
                </svg>
              </div>
              <div className="ml-3">
                <h3 className="text-sm font-medium text-red-800">获取实验详情失败</h3>
                <div className="mt-2 text-sm text-red-700">
                  <p>{error}</p>
                  <p className="mt-2">
                    <ButtonLink
                      href="/experiments"
                      variant="outline"
                      size="sm"
                    >
                      返回实验列表
                    </ButtonLink>
                  </p>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    )
  }

  if (!experiment) {
    return (
      <div className="py-8">
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
          <div className="text-center py-16">
            <h3 className="mt-2 text-lg font-medium text-gray-900">实验不存在或无权访问</h3>
            <p className="mt-1 text-sm text-gray-500">请检查实验ID是否正确，或联系管理员获取访问权限</p>
            <div className="mt-6">
              <ButtonLink
                href="/experiments"
                variant="primary"
              >
                返回实验列表
              </ButtonLink>
            </div>
          </div>
        </div>
      </div>
    )
  }

  const now = new Date()
  const startTime = new Date(experiment.startTime)
  const endTime = new Date(experiment.endTime)
  const isActive = now >= startTime
  const isEnded = now > endTime
  const canSubmitLate = experiment.allowLateSubmission && isEnded

  const experimentContent = experiment ? JSON.parse(experiment.stages[0]?.content as string || '{}') : {};

  return (
    <div className="py-8">
      <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
        <div className="flex justify-between items-center mb-6">
          <h1 className="text-2xl font-semibold text-gray-900">{experiment.title}</h1>
          
          {canManageExperimentResources && (
            <ButtonLink
              href={`/experiments/${experiment.id}/edit`}
              variant="primary"
            >
              编辑实验
            </ButtonLink>
          )}
        </div>
        
        <div className="bg-white shadow overflow-hidden sm:rounded-lg mb-6">
          <div className="px-4 py-5 sm:px-6">
            <div className="flex items-center justify-between">
              <div>
                <h3 className="text-lg leading-6 font-medium text-gray-900">实验详情</h3>
                <p className="mt-1 max-w-2xl text-sm text-gray-500">
                  由 {experiment.createdBy.name} 创建
                </p>
              </div>
              
              <div className="text-right">
                <p className="text-sm text-gray-500">
                  开始时间:
                  <span suppressHydrationWarning>
                    {formatDate(new Date(experiment.startTime))}
                  </span>
                </p>
                <p className="text-sm text-gray-500">
                  截止时间:
                  <span suppressHydrationWarning>
                    {formatDate(new Date(experiment.endTime))}
                  </span>
                </p>
                {experiment.allowLateSubmission && (
                  <p className="text-sm text-yellow-600">允许迟交</p>
                )}
              </div>
            </div>
          </div>
          
          <div className="border-t border-gray-200">
            <div className="bg-gray-50 px-4 py-3">
              <nav className="flex space-x-4">
                <button
                  onClick={(e) => {
                    e.preventDefault();
                    e.stopPropagation();
                    if (activeTab !== 'overview') {
                      setActiveTab('overview');
                    }
                  }}
                  className={`px-3 py-2 text-sm font-medium rounded-md ${
                    activeTab === 'overview'
                      ? 'bg-white shadow text-gray-800'
                      : 'text-gray-600 hover:text-gray-800'
                  }`}
                >
                  实验概述
                </button>
                <button
                  type="button"
                  onClick={() => setActiveTab('stages')}
                  className={`px-3 py-2 text-sm font-medium rounded-md ${
                    activeTab === 'stages'
                      ? 'bg-white shadow text-gray-800'
                      : 'text-gray-600 hover:text-gray-800'
                  }`}
                >
                  实验阶段
                </button>
                <button
                  onClick={() => setActiveTab('resources')}
                  className={`px-3 py-2 text-sm font-medium rounded-md ${
                    activeTab === 'resources'
                      ? 'bg-white shadow text-gray-800'
                      : 'text-gray-600 hover:text-gray-800'
                  }`}
                >
                  实验资源
                </button>
                <button
                  onClick={() => setActiveTab('announcements')}
                  className={`px-3 py-2 text-sm font-medium rounded-md ${
                    activeTab === 'announcements'
                      ? 'bg-white shadow text-gray-800'
                      : 'text-gray-600 hover:text-gray-800'
                  }`}
                >
                  实验公告
                </button>
                <button
                  onClick={() => setActiveTab('forum')}
                  className={`px-3 py-2 text-sm font-medium rounded-md ${
                    activeTab === 'forum'
                      ? 'bg-white shadow text-gray-800'
                      : 'text-gray-600 hover:text-gray-800'
                  }`}
                >
                  答疑论坛
                </button>
                {isTeacherOrAdmin && (
                  <button
                    onClick={() => setActiveTab('students')}
                    className={`px-3 py-2 text-sm font-medium rounded-md ${
                      activeTab === 'students'
                        ? 'bg-white shadow text-gray-800'
                        : 'text-gray-600 hover:text-gray-800'
                    }`}
                  >
                    学生完成情况
                  </button>
                )}
                {session?.user?.role === 'STUDENT' && (
                  <button
                    onClick={() => setActiveTab('history')}
                    className={`px-3 py-2 text-sm font-medium rounded-md ${
                      activeTab === 'history'
                        ? 'bg-white shadow text-gray-800'
                        : 'text-gray-600 hover:text-gray-800'
                    }`}
                  >
                    历史评测记录
                  </button>
                )}
              </nav>
            </div>
            
            <div className="px-4 py-5 sm:p-6">
              {/* 实验概述 */}
              {activeTab === 'overview' && (
                <div>
                  <h4 className="text-lg font-medium text-gray-900 mb-2">实验简介</h4>
                  <div
                    className="prose max-w-none"
                    dangerouslySetInnerHTML={{ __html: experiment.description || '<p>暂无简介</p>' }}
                  />
                </div>
              )}
              
              {/* 实验阶段 */}
              {activeTab === 'stages' && (
                <div>
                  <h4 className="text-lg font-medium text-gray-900 mb-4">实验阶段</h4>
                  
                  {(!isActive && !isTeacherOrAdmin) ? (
                    <div className="text-center py-4 text-yellow-600">
                      实验还未开始
                    </div>
                  ) : (
                    <div className="space-y-6">
                      {experiment.stages.map((stage) => (
                        <div key={stage.id} className="bg-gray-50 p-6 rounded-md">
                          <h5 className="text-lg font-medium text-gray-900">
                            {stage.title}
                          </h5>
                          <p className="mt-1 text-sm text-gray-500">
                            {stage.description || '暂无描述'}
                          </p>
                          
                          <div className="mt-4">
                            {!isActive && !isTeacherOrAdmin ? (
                              <Button disabled>
                                实验还未开始
                              </Button>
                            ) : (
                              <ButtonLink
                                href={`/experiments/${experiment.id}/stages/${stage.id}`}
                                disabled={!isActive && !isTeacherOrAdmin}
                              >
                                {isTeacherOrAdmin
                                  ? '查看阶段详情'
                                  : (isEnded && !canSubmitLate)
                                    ? '查看历史提交'
                                    : '开始实验'}
                              </ButtonLink>
                            )}
                          </div>
                        </div>
                      ))}
                    </div>
                  )}
                </div>
              )}
              
              {/* 实验资源 */}
              {activeTab === 'resources' && (
                <div>
                  <div className="flex justify-between items-center mb-4">
                    <h4 className="text-lg font-medium text-gray-900">实验资源</h4>
                    {canManageExperimentResources && (
                    <ResourceUploader
                      experimentId={experiment.id}
                      resources={experiment.resources || []} 
                      onResourceAdded={handleResourceAdded}   
                      onResourceDeleted={handleResourceDeleted} 
                      canManage={canManageExperimentResources} 
                    />
                    )}
                  </div>
                  {/* 资源列表 */}
                  {experiment.resources && experiment.resources.length > 0 ? (
                   <ul role="list" className="divide-y divide-gray-200">
                     {experiment.resources.map((resource) => (
                       <li key={resource.id} className="py-4 flex justify-between items-center">
                         <div>
                           <a href={resource.url} target="_blank" rel="noopener noreferrer" className="text-sm font-medium text-primary-600 hover:text-primary-500">
                             {resource.title}
                           </a>
                           <p className="text-sm text-gray-500">{resource.type} - {formatDate(new Date(resource.createdAt))}</p>
                         </div>
                         {canManageExperimentResources && (
                           <Button
                             variant="outline"
                             className="text-red-600 hover:text-red-700 hover:bg-red-50 border-red-300 hover:border-red-400"
                             size="sm"
                             onClick={async () => {
                               if (confirm(`确定要删除资源 "${resource.title}"吗？`)) {
                                 try {
                                   const response = await fetch(`/api/experiments/${experiment.id}/resources/${resource.id}`, {
                                     method: 'DELETE',
                                   });
                                   if (!response.ok) {
                                     throw new Error('删除资源失败');
                                   }
                                   handleResourceDeleted(resource.id);
                                 } catch (error) {
                                   toast.error('删除资源失败');
                                   console.error('删除资源失败:', error);
                                 }
                               }
                             }}
                           >
                             删除
                           </Button>
                         )}
                       </li>
                     ))}
                   </ul>
                  ) : (
                   <p className="text-sm text-gray-500">暂无实验资源。</p>
                  )}
                </div>
              )}
              
              {/* 实验公告 */}
              {activeTab === 'announcements' && (
                <div>
                  <h4 className="text-lg font-medium text-gray-900 mb-4">实验公告</h4>
                  
                  <AnnouncementList
                    experimentId={experiment.id}
                    canManage={isTeacherOrAdmin && isExperimentOwner}
                  />
                </div>
              )}
              
              {/* 答疑论坛 */}
              {activeTab === 'forum' && (
                <div>
                  <h4 className="text-lg font-medium text-gray-900 mb-4">答疑论坛</h4>
                  
                  <div className="flex justify-between items-center mb-6">
                    <p className="text-sm text-gray-600">
                      在这里提问与实验相关的问题，教师和其他同学可以回答
                    </p>
                    <ButtonLink
                      href={`/forum/new?experimentId=${experiment.id}`}
                    >
                      提出问题
                    </ButtonLink>
                  </div>
                  
                  <div className="bg-white p-4 rounded-lg border border-gray-200">
                    <ButtonLink
                      href={`/forum?experimentId=${experiment.id}`}
                      variant="ghost"
                      className="flex justify-between items-center text-primary-600 hover:text-primary-800"
                    >
                      <span>查看该实验的所有问题</span>
                      <span className="text-sm">→</span>
                    </ButtonLink>
                  </div>
                </div>
              )}

              {/* 学生完成情况 */}
              {activeTab === 'students' && (
                <div>
                  <div className="flex justify-between items-center mb-4">
                    <h4 className="text-lg font-medium text-gray-900">学生实验完成情况</h4>
                    <div className="flex space-x-2">
                      <button
                        onClick={() => setViewMode('individual')}
                        className={`px-3 py-1 text-sm rounded-md ${
                          viewMode === 'individual'
                            ? 'bg-primary-100 text-primary-800'
                            : 'bg-gray-100 text-gray-600 hover:bg-gray-200'
                        }`}
                      >
                        按学生
                      </button>
                      <button
                        onClick={() => setViewMode('group')}
                        className={`px-3 py-1 text-sm rounded-md ${
                          viewMode === 'group'
                            ? 'bg-primary-100 text-primary-800'
                            : 'bg-gray-100 text-gray-600 hover:bg-gray-200'
                        }`}
                      >
                        按小组
                      </button>
                    </div>
                  </div>
                  
                  {(loadingSubmissions || loadingGroups) ? (
                    <div className="text-center py-8">
                      <div className="flex justify-center">
                        <div className="animate-spin rounded-full h-8 w-8 border-t-2 border-b-2 border-primary-600"></div>
                      </div>
                      <p className="mt-2 text-gray-600">加载学生提交数据中...</p>
                    </div>
                  ) : submissionError ? (
                    <div className="bg-red-50 border border-red-200 rounded-md p-4">
                      <div className="flex">
                        <div className="flex-shrink-0">
                          <svg className="h-5 w-5 text-red-400" viewBox="0 0 20 20" fill="currentColor">
                            <path fillRule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zM8.707 7.293a1 1 0 00-1.414 1.414L8.586 10l-1.293 1.293a1 1 0 101.414 1.414L10 11.414l1.293 1.293a1 1 0 001.414-1.414L11.414 10l1.293-1.293a1 1 0 00-1.414-1.414L10 8.586 8.707 7.293z" clipRule="evenodd" />
                          </svg>
                        </div>
                        <div className="ml-3">
                          <p className="text-sm text-red-700">{submissionError}</p>
                          <button
                            onClick={fetchStudentSubmissions}
                            className="mt-2 text-sm font-medium text-red-700 hover:text-red-600"
                          >
                            重试
                          </button>
                        </div>
                      </div>
                    </div>
                  ) : (
                    <>
                      {/* 统计信息卡片 */}
                      {submissionStats && (
                        <div className="grid grid-cols-1 md:grid-cols-4 gap-4 mb-6">
                          <div className="bg-blue-50 p-4 rounded-lg">
                            <h5 className="text-sm font-medium text-blue-800">提交学生数</h5>
                            <p className="mt-1 text-lg font-semibold text-blue-900">
                              {submissionStats.studentsWhoSubmittedAtLeastOnce ?? '0'} / {submissionStats.totalAuthorizedStudents ?? '0'}
                            </p>
                            <p className="text-xs text-blue-700">
                              完成率: {
                                (typeof submissionStats.studentsWhoSubmittedAtLeastOnce === 'number' && 
                                 typeof submissionStats.totalAuthorizedStudents === 'number' && 
                                 submissionStats.totalAuthorizedStudents > 0)
                                  ? ((submissionStats.studentsWhoSubmittedAtLeastOnce / submissionStats.totalAuthorizedStudents) * 100).toFixed(2) + '%'
                                  : (submissionStats.studentsWhoSubmittedAtLeastOnce > 0 && submissionStats.totalAuthorizedStudents === 0)
                                    ? '100.00%' // Edge case: submitters exist but no authorized (e.g. admin testing)
                                    : 'N/A'
                              }
                            </p>
                          </div>
                          
                          <div className="bg-green-50 p-4 rounded-lg">
                            <h5 className="text-sm font-medium text-green-800">已提交快照总数</h5>
                            <p className="mt-1 text-lg font-semibold text-green-900">
                              {submissionStats.totalFormalSubmissions ?? '0'}
                            </p>
                          </div>
                          
                          <div className="bg-yellow-50 p-4 rounded-lg">
                            <h5 className="text-sm font-medium text-yellow-800">已评阅快照数</h5>
                            <p className="mt-1 text-lg font-semibold text-yellow-900">
                              {submissionStats.statusCounts?.GRADED ?? '0'}
                            </p>
                          </div>
                          
                          <div className="bg-purple-50 p-4 rounded-lg">
                            <h5 className="text-sm font-medium text-purple-800">学生最高分平均</h5>
                            <p className="mt-1 text-lg font-semibold text-purple-900">
                              {typeof submissionStats.avgScoreOfHighestSubmissions === 'number'
                                ? submissionStats.avgScoreOfHighestSubmissions.toFixed(2)
                                : '暂无评分'}
                            </p>
                          </div>
                        </div>
                      )}
                      
                      {/* 学生提交列表 */}
                      {viewMode === 'individual' && (
                        <>
                          {studentSubmissions.length === 0 ? (
                            <div className="text-center py-6 bg-gray-50 rounded-lg">
                              <p className="text-gray-500">暂无学生提交记录</p>
                            </div>
                          ) : (
                            <div className="overflow-x-auto">
                              <div className="inline-block min-w-full align-middle">
                                <div className="overflow-hidden shadow ring-1 ring-black ring-opacity-5 md:rounded-lg">
                                  <table className="min-w-full divide-y divide-gray-300">
                                    <thead className="bg-gray-50">
                                      <tr>
                                        <th scope="col" className="py-3.5 pl-4 pr-3 text-left text-sm font-semibold text-gray-900 sm:pl-6">
                                          学生姓名
                                        </th>
                                        <th scope="col" className="px-3 py-3.5 text-left text-sm font-semibold text-gray-900">
                                          提交时间
                                        </th>
                                        <th scope="col" className="px-3 py-3.5 text-left text-sm font-semibold text-gray-900">
                                          状态
                                        </th>
                                        <th scope="col" className="px-3 py-3.5 text-left text-sm font-semibold text-gray-900">
                                          得分
                                        </th>
                                        <th scope="col" className="relative py-3.5 pl-3 pr-4 sm:pr-6">
                                          <span className="sr-only">操作</span>
                                        </th>
                                      </tr>
                                    </thead>
                                    <tbody className="divide-y divide-gray-200 bg-white">
                                      {studentSubmissions.length > 0 ? studentSubmissions.map((submission) => (
                                        <tr key={submission.id}>
                                          <td className="whitespace-nowrap py-4 pl-4 pr-3 text-sm font-medium text-gray-900 sm:pl-6">
                                            {submission.user?.name || '(未设置姓名)'} 
                                            <span className="text-xs text-gray-500 block">
                                              {submission.user?.email}
                                            </span>
                                          </td>
                                          <td className="whitespace-nowrap px-3 py-4 text-sm text-gray-500">
                                            <span suppressHydrationWarning>
                                              {submission.submittedAt
                                                ? new Date(submission.submittedAt).toLocaleString()
                                                : 'N/A'}
                                            </span>
                                          </td>
                                          <td className="whitespace-nowrap px-3 py-4 text-sm text-gray-500">
                                            {getStatusText(submission.status)}
                                          </td>
                                          <td className="whitespace-nowrap px-3 py-4 text-sm text-gray-500">
                                            <GradeInput
                                              submissionId={submission.id}
                                              experimentId={experiment.id}
                                              currentScore={submission.score}
                                              studentName={submission.user?.name || submission.user?.email}
                                              onScoreUpdated={(newScore) => handleScoreUpdate(submission.id, newScore)}
                                            />
                                          </td>
                                          <td className="relative whitespace-nowrap py-4 pl-3 pr-4 text-right text-sm font-medium sm:pr-6">
                                            <ButtonLink
                                              href={`/experiments/${experiment.id}/submissions/${submission.id}`}
                                              variant="ghost"
                                              className="text-primary-600 hover:text-primary-900"
                                              size="sm"
                                            >
                                              查看详情/评分
                                            </ButtonLink>
                                          </td>
                                        </tr>
                                      )) : (
                                        <tr>
                                          <td colSpan={5} className="text-center py-6 bg-gray-50 text-gray-500">
                                            暂无学生提交记录
                                          </td>
                                        </tr>
                                      )}
                                    </tbody>
                                  </table>
                                </div>
                              </div>
                            </div>
                          )}
                          
                          {/* 刷新按钮 */}
                          <div className="mt-6 text-center">
                            <Button
                              onClick={fetchStudentSubmissions}
                              variant="outline"
                            >
                              刷新数据
                            </Button>
                          </div>
                        </>
                      )}

                      {/* 小组提交列表 */}
                      {viewMode === 'group' && (
                        <>
                          {groupSubmissions.length === 0 ? (
                            <div className="text-center py-6 bg-gray-50 rounded-lg">
                              <p className="text-gray-500">暂无小组信息</p>
                            </div>
                          ) : (
                            <div className="space-y-6">
                              {groupSubmissions.map((group) => (
                                <div key={group.id} className="bg-white border border-gray-200 rounded-lg p-6">
                                  <div className="flex justify-between items-start mb-4">
                                    <div>
                                      <h5 className="text-lg font-medium text-gray-900">{group.name}</h5>
                                      <p className="text-sm text-gray-500">{group.description || '暂无描述'}</p>
                                    </div>
                                    <GroupGradeInput
                                      experimentId={experiment.id}
                                      groupMembers={group.members.map((member: any) => ({
                                        id: member.user.id,
                                        name: member.user.name,
                                        email: member.user.email,
                                        submissionId: member.submission?.id,
                                        currentScore: member.submission?.score
                                      }))}
                                      groupName={group.name}
                                      onScoresUpdated={handleGroupScoresUpdate}
                                    />
                                  </div>
                                  
                                  <div className="overflow-x-auto">
                                    <table className="min-w-full divide-y divide-gray-300">
                                      <thead className="bg-gray-50">
                                        <tr>
                                          <th scope="col" className="py-2 pl-4 pr-3 text-left text-sm font-semibold text-gray-900">
                                            成员姓名
                                          </th>
                                          <th scope="col" className="px-3 py-2 text-left text-sm font-semibold text-gray-900">
                                            角色
                                          </th>
                                          <th scope="col" className="px-3 py-2 text-left text-sm font-semibold text-gray-900">
                                            状态
                                          </th>
                                          <th scope="col" className="px-3 py-2 text-left text-sm font-semibold text-gray-900">
                                            得分
                                          </th>
                                          <th scope="col" className="relative py-2 pl-3 pr-4">
                                            <span className="sr-only">操作</span>
                                          </th>
                                        </tr>
                                      </thead>
                                      <tbody className="divide-y divide-gray-200 bg-white">
                                        {group.members.map((member: any) => (
                                          <tr key={member.id}>
                                            <td className="whitespace-nowrap py-2 pl-4 pr-3 text-sm font-medium text-gray-900">
                                              {member.user.name || '(未设置姓名)'}
                                              <span className="text-xs text-gray-500 block">
                                                {member.user.email}
                                              </span>
                                            </td>
                                            <td className="whitespace-nowrap px-3 py-2 text-sm text-gray-500">
                                              {member.role === 'LEADER' ? '组长' : '成员'}
                                            </td>
                                            <td className="whitespace-nowrap px-3 py-2 text-sm text-gray-500">
                                              {member.submission ? getStatusText(member.submission.status) : '未提交'}
                                            </td>
                                            <td className="whitespace-nowrap px-3 py-2 text-sm text-gray-500">
                                              {member.submission ? (
                                                <GradeInput
                                                  submissionId={member.submission.id}
                                                  experimentId={experiment.id}
                                                  currentScore={member.submission.score}
                                                  studentName={member.user.name || member.user.email}
                                                  onScoreUpdated={(newScore) => handleScoreUpdate(member.submission.id, newScore)}
                                                />
                                              ) : (
                                                <span className="text-gray-400">未提交</span>
                                              )}
                                            </td>
                                            <td className="relative whitespace-nowrap py-2 pl-3 pr-4 text-right text-sm font-medium">
                                              {member.submission && (
                                                <ButtonLink
                                                  href={`/experiments/${experiment.id}/submissions/${member.submission.id}`}
                                                  variant="ghost"
                                                  className="text-primary-600 hover:text-primary-900"
                                                  size="sm"
                                                >
                                                  查看详情
                                                </ButtonLink>
                                              )}
                                            </td>
                                          </tr>
                                        ))}
                                      </tbody>
                                    </table>
                                  </div>
                                </div>
                              ))}
                            </div>
                          )}
                          
                          {/* 刷新按钮 */}
                          <div className="mt-6 text-center">
                            <Button
                              onClick={fetchGroupSubmissions}
                              variant="outline"
                            >
                              刷新数据
                            </Button>
                          </div>
                        </>
                      )}
                    </>
                  )}
                </div>
              )}
              {activeTab === 'history' && session?.user?.role === 'STUDENT' && (
                <HistoryView />
              )}
            </div>
          </div>
        </div>
      </div>
    </div>
  )
} 